package hhf.flex.soundapi.ui {
	import flash.display.Graphics;
	import flash.display.GraphicsPathCommand;
	import flash.events.Event;
	import flash.media.SoundMixer;
	import flash.utils.ByteArray;
	
	import mx.core.UIComponent;

	[Style(name="fillLeftColor", type="uint", format="Color ", inherit="yes")]
	[Style(name="fillRightColor", type="uint", format="Color ", inherit="yes")]

	public class Spectrum  extends UIComponent {
		public function Spectrum() {
			super();
			this.setStyle("fillLeftColor", 0x6600CC);
			this.setStyle("fillRightColor", 0xCC0066);
			addEventListener(Event.ENTER_FRAME, onEnterFrame);
		}

		/**
		 * Synchronisation sur le render de la scene
		 */
		protected function onEnterFrame(e:Event):void {
			try {
				var bytes:ByteArray = new ByteArray();
				SoundMixer.computeSpectrum(bytes, false, 0); // 2048 buffer
				var g:Graphics = this.graphics;
				g.clear();
				var length:int = bytes.length/8; // 256 float sur 4octets donc 2048/(4*2) (left et right)
				var verticalCenter:Number = this.height/2; // Centre vertical
				var samplesize:Number = this.width/length;
				var drawCoordsL:Vector.<Number> = new Vector.<Number>(); 
				var drawCommandsL:Vector.<int> = new Vector.<int>(); 
				var drawCoordsR:Vector.<Number> = new Vector.<Number>(); 
				var drawCommandsR:Vector.<int> = new Vector.<int>();
				drawCoordsL.push(0, verticalCenter);
				drawCoordsR.push(0, verticalCenter);
				drawCommandsL.push(GraphicsPathCommand.MOVE_TO);
				drawCommandsR.push(GraphicsPathCommand.MOVE_TO);
				while(bytes.bytesAvailable) {
					var currentX:int = bytes.position*samplesize;
					var floatLeft:Number = bytes.readFloat(); // lit 4 octets 
					var floatRight:Number = bytes.readFloat(); // lit 4 octets
					drawCoordsL.push(currentX, verticalCenter - floatLeft * verticalCenter);
					drawCoordsR.push(currentX, verticalCenter - floatRight * verticalCenter);
					drawCommandsL.push(GraphicsPathCommand.LINE_TO);
					drawCommandsR.push(GraphicsPathCommand.LINE_TO);
				}
				g.lineStyle(1, getStyle("fillLeftColor"));
				g.beginFill(getStyle("fillLeftColor"), 0.5);
				g.drawPath(drawCommandsL, drawCoordsL);
				g.lineStyle(1, getStyle("fillRightColor"));
				g.beginFill(getStyle("fillRightColor"), 0.5);
				g.drawPath(drawCommandsR, drawCoordsR);
			}catch(e:Error) {}
		}
	}
}